package com.example.clothingmanager.config;

import com.example.clothingmanager.bean.User;
import com.example.clothingmanager.dao.UserDao;
import com.example.clothingmanager.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Huangyt
 * @version 1.0
 * @date 2020/5/11 21:24
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    UserDao userDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行授权逻辑");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        //是从doGetAuthenticationInfo方法返回的user得到的
        System.out.println("subject.getPrincipal();" + subject.getPrincipal());
        User user = (User) subject.getPrincipal();
//        User dbUser = userService.findById(user.getId());
        //添加资源的授权字符串
        System.out.println(user.getAuth());
        info.addStringPermission(user.getAuth());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
        System.out.println("执行认证逻辑");

        //subject.login(token) 传来的token
        UsernamePasswordToken token = (UsernamePasswordToken) arg0;

        //判断用户名是否存在
        User user = userDao.findByAccount(token.getUsername());
        if(user==null){
            //用户名不存在
            //返回 null， shiro 底层会抛出UnKnowAccountException异常
            return null;
        }

        /*
         * 2、判断密码是否正确
         * 1)、错误的话 shiro 底层会抛出IncorrectCredentialsException异常
         * 2)、正确的话返回true
         */
        return new SimpleAuthenticationInfo(user/*方法的携带信息*/, user.getPassword(), ""/*shiro的名称*/);
    }
}
